/*
 * PositionDAO.java
 *
 * Created on March 8, 2007, 10:15 PM
 *
 */

package edu.byu.isys413.group1E.data;

import edu.byu.isys413.group1E.handlers.*;
import java.sql.*;
import java.util.ArrayList;

/**Reads and writes PositionBO data to and from the database.
 *
 * @author Travis Kulbeth
 */
public class PositionDAO {
    
    /** Contains an instance of PositionDAO*/
    private static PositionDAO instance = null;
    
    /** Creates a new instance of PositionDAO */
    public PositionDAO() {
    }
    
    /**Retrieves an instance of the PositionDAO object
     *
     * @return a current singleton instance of the PositionDAO class
     */
    public static synchronized PositionDAO getInstance() {
        if (instance == null) {
            instance = new PositionDAO();
        }
        return instance;
    }

    ///////////////////////////////////////////////////////////////////////////////
    /////////   CREATE
    /**
     * Creates a new PositionBO object with a newly generated GUID.
     * 
     * @return a newly created PositionBO with unique GUID
     * @throws java.lang.Exception to catch any errors in the creation process.
     */
    public PositionBO create() throws Exception{
        String id = GUID.generate();
        PositionBO bo = new PositionBO(id);
        Cache c = Cache.getInstance();
        c.put(bo.getPositionID(), bo);
        return bo;
    }
    
    //////////////////////////////////////////////////////////////////////////////
    //////////   READ
    /**
     * This is the public read statement.  It loads an existing Position record
     * from the database based on the Position id and returns a PositionBO.
     * 
     * @return a PositionBO containing the information extracted from the requested
     * tuple in the DB.
     * @param id contains the unique identifier for the record to be read from the DB.
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws edu.byu.isys413.group1E.handlers.ConnectionPoolException catches any errors with the connection
     */
    public synchronized PositionBO read(String id) throws DataException, ConnectionPoolException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        PositionBO pos = (PositionBO)c.get(id);
        if (pos != null){
            return pos;                                                        // if so, return it immediately
        }
        
        //otherwise, get it from the database
        try {
            Connection conn = ConnectionPool.getInstance().get();             // retrieve a database connection from the pool
            pos = this.read(id, conn);                                              // call read with a connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            //rollback
            throw new DataException("Could not retrieve record for id = " + id, e);
        }catch (ConnectionPoolException x) {
            //rollback
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return pos;
    }
    
    
    /**
     * This is the public read statement.  It loads an existing Position record
     * from the database based on the Position id, using an already existing connection to the DB,
     * and returns a PositionBO.
     * 
     * 
     * @return PositionBO
     * @param id contains the given id for the Position to be read
     * @param conn contains an already open connection to the DB
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */
    synchronized PositionBO read(String id, Connection conn) throws SQLException, DataException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        PositionBO pos = (PositionBO)c.get(id);
        if (pos != null){
            return pos;                                                        // if so, return it immediately
        }
        
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM Position_tbl WHERE PositionID = '" + id + "'");
        conn.commit();
        
        //build the object from the result set
        if (rs.next()) {
            pos = new PositionBO(rs.getString("PositionID"));
            pos.setTitle(rs.getString("Title"));
            pos.setSalary(rs.getDouble("Salary"));
            pos.setAlreadyInDB(true);
            pos.setIsDirty(false);
            
            // save to the cache
            c.put(pos.getPositionID(), pos);
        }else{
            throw new DataException("Object was not found in the database.");
        }
        stmt.close();
        // return the BO
        return pos;
    }
    
    /**
     * This is a public method to retrieve a list of all Positions in the DB.
     * 
     * @return a list of all Positions from the DB.
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     * @throws edu.byu.isys413.group1E.handlers.ConnectionPoolException catches any errors with the connection
     */
    public synchronized ArrayList<PositionBO> readAllPositions() throws DataException, SQLException, ConnectionPoolException{
        ArrayList<PositionBO> posList = new ArrayList<PositionBO>();
        //now build the query
        String query = "SELECT * FROM Position_tbl";

        Connection conn = ConnectionPool.getInstance().get();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        conn.commit();
        
        //extract the elements from the result set and build a list of results
        //build the object from the result set
        while (rs.next()) {
            PositionBO pos = new PositionBO(rs.getString("PositionID"));
            pos = new PositionBO(rs.getString("PositionID"));
            pos.setTitle(rs.getString("Title"));
            pos.setSalary(rs.getDouble("Salary"));
            pos.setAlreadyInDB(true);
            pos.setIsDirty(false);
            
            // save to the list
            posList.add(pos);
        }//while
        
        stmt.close();
        ConnectionPool.getInstance().release(conn);
        return posList;
    }
    
    //////////////////////////////////
    ///   UPDATE
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) wants to save or update an object
     * into the database.
     * 
     * @param posIn is a PositionBO object to be saved
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws edu.byu.isys413.group1E.handlers.ConnectionPoolException catches any errors with the connection
     */
    public synchronized void save(PositionBO posIn) throws DataException, ConnectionPoolException {
        
        try {
            Connection conn = ConnectionPool.getInstance().get();
            try {
                this.save(posIn, conn);                                   // call save with a connection
                conn.commit();
            } catch (SQLException ex) {
                conn.rollback();
                ex.printStackTrace();
                throw new SQLException();
            } catch (ConnectionPoolException ex) {
                conn.rollback();
                ex.printStackTrace();
            } catch (DataException ex) {
                conn.rollback();
                ex.printStackTrace();
            }
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            throw new DataException("Error saving record for Position ID =" + posIn.getPositionID(), e);
        }catch (ConnectionPoolException x){
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return;
    }
    
    /**
     * This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     * 
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the PositionDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.
     * 
     * @param pos contains the PositionBO to be saved
     * @param conn contains the Connection that has been established to the DB
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     * @throws edu.byu.isys413.group1E.handlers.ConnectionPoolException catches any errors with the connection
     */
    synchronized void save(PositionBO pos, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // run update or insert
        if (pos.isIsDirty()) {
            if (pos.isAlreadyInDB()) {
                update(pos, conn);
            }else{
                insert(pos, conn);
            }
            // set the dirty flag to false now that we've saved it
            pos.setIsDirty(false);
        }

                
        // touch the cache for the object
        Cache c = Cache.getInstance();
        c.put(pos.getPositionID(), pos);
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     * 
     * 
     * @param pos contains the PositionBO to be updated to the DB
     * @param conn contains the connection already established with the DB
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */
    private synchronized void update(PositionBO pos, Connection conn) throws SQLException, DataException {
        //update the DB
        PreparedStatement pstmt = conn.prepareStatement("UPDATE Position_tbl SET Title = ?, Salary = ? WHERE PositionID = ?");
        pstmt.setString(1, pos.getTitle());
        pstmt.setDouble(2, pos.getSalary());
        pstmt.setString(3, pos.getPositionID());
        pstmt.executeUpdate();
        pstmt.close();
        pos.setAlreadyInDB(true);
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     * 
     * @param pos contains the PositionBO to be updated to the DB
     * @param conn contains the connection already established with the DB
     * @throws edu.byu.isys413.group1E.handlers.DataException handles any errors from data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */
    private synchronized void insert(PositionBO pos, Connection conn) throws SQLException, DataException {
        //update the DB
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Position_tbl (PositionID, Title, Salary)" +
                "VALUES (?, ?, ?)");
        pstmt.setString(1, pos.getPositionID());
        pstmt.setString(2, pos.getTitle());
        pstmt.setDouble(3, pos.getSalary());
        pstmt.executeUpdate();
        pstmt.close();
        // tell the object that it's now in the db (so we call update next time not insert)
        pos.setAlreadyInDB(true);
    }
    
    
    ///////////////////////////////////////////////////////////////////////////////
    /////////   DELETE
    
    /** I did not include the DELETE functionality intentionally due to instructions received, as well as
     * to protect the integrity of the data.
     */
}
